package com.mifan.controller;/*
 * @Author Milan
 * @Date 2024/9/13 16:54
 */

import com.mifan.common.Results;
import com.mifan.utils.JwtTokenUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class LoginController {

    @Resource
    private AuthenticationManager authenticationManager;

    @GetMapping("/login")
    public Results login(String username, String password) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(token);
       if(authenticate.isAuthenticated()) {
           String tokenStr = JwtTokenUtil.generateToken(username);
           return Results.success("登录成功", tokenStr);
       }
         return Results.failure("登录失败");
    }

    @GetMapping("/logout")
    public Results logout() {
        SecurityContextHolder.clearContext();
        return Results.success("退出成功");
    }


}
